import 'package:dio/dio.dart';

// import 'package:flutter/foundation.dart';
// import 'package:flutter/widgets.dart';
import 'app_config.dart';

class ApiClient {
  static final ApiClient _instance = ApiClient._internal();

  factory ApiClient() => _instance;

  ApiClient._internal();

  Dio? _dio; // 延迟初始化，避免 LateInitializationError
  _AuthInterceptor? _authInterceptor; // 同上
  bool _initialized = false;
  Function()? _onUnauthorized;

  void _ensureInitialized() {
    if (_initialized) return;
    _dio = Dio(
      BaseOptions(
        baseUrl: AppConfig.baseUrl,
        connectTimeout: AppConfig.connectTimeout,
        receiveTimeout: AppConfig.receiveTimeout,
        sendTimeout: AppConfig.sendTimeout,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ),
    );

    // 创建拦截器实例
    _authInterceptor = _AuthInterceptor();

    // 添加拦截器
    _dio!.interceptors.addAll([
      _LogInterceptor(),
      _authInterceptor!,
      _ErrorInterceptor(),
    ]);
    _initialized = true;
  }

  void init() {
    _ensureInitialized();
  }

  // 设置认证token
  void setAuthToken(String token) {
    _ensureInitialized();
    _authInterceptor!.setToken(token);
  }

  // 清除认证token
  void clearAuthToken() {
    _ensureInitialized();
    _authInterceptor!.clearToken();
  }

  // 设置401错误回调
  void setUnauthorizedCallback(Function() callback) {
    _onUnauthorized = callback;
  }

  // 检查token状态
  void checkTokenStatus() {
    _ensureInitialized();
    if (_authInterceptor!._accessToken != null) {
      print(
        '✅ Token已设置: ${_authInterceptor!._accessToken!.substring(0, 20)}...',
      );
    } else {
      print('❌ Token未设置');
    }
  }

  Dio get dio {
    _ensureInitialized();
    return _dio!;
  }

  // GET 请求
  Future<Response> get(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onReceiveProgress,
  }) {
    _ensureInitialized();
    return _dio!.get(
      path,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
      onReceiveProgress: onReceiveProgress,
    );
  }

  // POST 请求
  Future<Response> post(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) {
    _ensureInitialized();
    return _dio!.post(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
      onSendProgress: onSendProgress,
      onReceiveProgress: onReceiveProgress,
    );
  }

  // PUT 请求
  Future<Response> put(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) {
    _ensureInitialized();
    return _dio!.put(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
      onSendProgress: onSendProgress,
      onReceiveProgress: onReceiveProgress,
    );
  }

  // DELETE 请求
  Future<Response> delete(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) {
    _ensureInitialized();
    return _dio!.delete(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
    );
  }

  // 文件上传
  Future<Response> upload(
    String path, {
    required FormData formData,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) {
    _ensureInitialized();
    // 覆盖默认的 application/json 头，使用 multipart/form-data
    final Options effectiveOptions = (options ?? Options()).copyWith(
      contentType: Headers.multipartFormDataContentType,
    );
    return _dio!.post(
      path,
      data: formData,
      queryParameters: queryParameters,
      options: effectiveOptions,
      cancelToken: cancelToken,
      onSendProgress: onSendProgress,
      onReceiveProgress: onReceiveProgress,
    );
  }
}

// 日志拦截器
class _LogInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (AppConfig.isDebug) {
      print('🌐 API Request: ${options.method} ${options.uri}');
      print('📤 Headers: ${options.headers}');
      if (options.data != null) {
        print('📦 Data: ${options.data}');
      }
    }
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (AppConfig.isDebug) {
      print(
        '✅ API Response: ${response.statusCode} ${response.requestOptions.uri}',
      );
      print('📥 Data: ${response.data}');
    }
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (AppConfig.isDebug) {
      print('❌ API Error: ${err.type} ${err.message}');
      print('🔗 URL: ${err.requestOptions.uri}');
    }
    handler.next(err);
  }
}

// 认证拦截器
class _AuthInterceptor extends Interceptor {
  String? _accessToken;

  void setToken(String token) {
    _accessToken = token;
  }

  void clearToken() {
    _accessToken = null;
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 添加认证token
    if (_accessToken != null) {
      options.headers['Authorization'] = 'Bearer $_accessToken';
      options.headers['clientid'] = AppConfig.clientId;
      print('🔐 添加认证Token到请求头: Bearer ${_accessToken!.substring(0, 20)}...');
      print('🔐 添加clientid到请求头: ${AppConfig.clientId}');
    } else {
      print('⚠️ 没有设置认证Token');
    }
    handler.next(options);
  }
}

// 错误处理拦截器
class _ErrorInterceptor extends Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    // 统一错误处理
    switch (err.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        // 超时错误
        print('⏰ 请求超时: ${err.message}');
        break;
      case DioExceptionType.badResponse:
        // 服务器错误
        final statusCode = err.response?.statusCode;
        switch (statusCode) {
          case 401:
            // 未授权，清除token并跳转到401页面
            print('🔒 401未授权错误，清除用户登录状态');
            _handleUnauthorized();
            break;
          case 403:
            // 禁止访问
            print('🚫 403禁止访问');
            break;
          case 404:
            // 资源不存在
            print('🔍 404资源不存在');
            break;
          case 500:
            // 服务器内部错误
            print('💥 500服务器内部错误');
            break;
        }
        break;
      case DioExceptionType.cancel:
        // 请求被取消
        print('❌ 请求被取消');
        break;
      case DioExceptionType.connectionError:
        // 连接错误
        print('🌐 连接错误: ${err.message}');
        break;
      case DioExceptionType.badCertificate:
        // 证书错误
        print('🔐 证书错误: ${err.message}');
        break;
      case DioExceptionType.unknown:
        // 未知错误
        print('❓ 未知错误: ${err.message}');
        break;
    }
    handler.next(err);
  }

  void _handleUnauthorized() {
    // 清除认证token
    final apiClient = ApiClient();
    apiClient.clearAuthToken();

    // 调用401错误回调
    if (apiClient._onUnauthorized != null) {
      apiClient._onUnauthorized!();
    }

    print('🔄 已触发401错误处理');
  }
}
